import {
  pageUsers,
  getUserById,
  deleteUser,
  resetUserPassword,
  updateUserStatus,
  updateUserPassword,
} from "@/services/system/api";
import { PlusOutlined } from "@ant-design/icons";
import type {
  ActionType,
  ProColumns,
  ProDescriptionsItemProps,
} from "@ant-design/pro-components";
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
  TableDropdown,
} from "@ant-design/pro-components";
import { FormattedMessage, useIntl } from "@umijs/max";
import { Button, Drawer, Input, message, Modal } from "antd";
import React, { useRef, useState, useEffect } from "react";
import AddForm from "./components/AddForm";
import { UserVO } from "../constants";
import { set } from "lodash";

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<UserVO>();
  const [selectedRowsState, setSelectedRows] = useState<UserVO[]>([]);
  const [editRow, setEditRow] = useState<UserVO>();

  const queryPageData = async (pageParams: any) => {
    try {
      const response = await pageUsers(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      return response.data;
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: "request.error.retry" }));
    }
  };

  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    // console.log(params, sorter, filter);
    // const { current, pageSize, customerCode, customerName, customerStatus } = params
    // let queryParams = {};
    // if (current !== undefined) queryParams.current = current;
    // if (pageSize !== undefined) queryParams.pageSize = pageSize;
    // if (customerCode !== undefined) queryParams.likeCode = customerCode;
    // if (customerName !== undefined) queryParams.likeName = customerName;
    // if (customerStatus !== undefined) queryParams.status = Number(customerStatus);
    return await queryPageData(params);
  };

  const makeActive = (record: UserVO) => {
    Modal.confirm({
      title: "确认操作",
      content: `确定要重置该用户的密码吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const hide = message.loading("Processing...");
        try {
          // const status = record.customerStatus === 1 ? 0 : 1;
          const response = await updateUserStatus(record);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(
                intl.formatMessage({ id: "request.error.create" })
              );
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          message.success(`重置密码成功`);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: "request.error.retry" }));
        }
      },
    });
  };
  const makeResetPwd = (record: UserVO) => {
    Modal.confirm({
      title: "确认操作",
      content: `确定要重置该用户的密码吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const hide = message.loading("Processing...");
        try {
          // const status = record.customerStatus === 1 ? 0 : 1;
          const response = await resetUserPassword(record.id);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(
                intl.formatMessage({ id: "request.error.create" })
              );
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          message.success(`重置密码成功`);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: "request.error.retry" }));
        }
      },
    });
  };

  const changeUserStatus = async (record: UserVO) => {
   
    try {
      // const status = record.customerStatus === 1 ? 0 : 1;
      const response = await updateUserStatus(record);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
          return false;
        }
      }
    
      message.success(intl.formatMessage({ id: "request.success.operating"}));
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: "request.error.retry" }));
    }
  };

  const deleteListData = async (record: UserVO) => {   
    
    Modal.confirm({
      title: "确认操作",
      content: `确定要删除该用户吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const hide = message.loading("Processing...");
        try {
          // const status = record.customerStatus === 1 ? 0 : 1;
          const response = await deleteUser(record.id);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(
                intl.formatMessage({ id: "request.error.create" })
              );
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: "request.error.retry" }));
        }
      },
    });
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<UserVO>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.user.username"
          defaultMessage="Login Name"
        />
      ),
      dataIndex: "username",
      key: "username",
    },
    {
      title: (
        <FormattedMessage id="pages.user.nickname" defaultMessage="Nickname" />
      ),
      dataIndex: "nickname",
      key: "nickname",
      search: false,
    },
    {
      title: <FormattedMessage id="pages.remark" defaultMessage="Remark" />,
      dataIndex: "remark",
      key: "remark",
      search: false,
    },
    {
      title: <FormattedMessage id="pages.user.email" defaultMessage="Email" />,
      dataIndex: "email",
      key: "email",
      search: false,
    },
    {
      title: (
        <FormattedMessage id="pages.user.mobile" defaultMessage="Mobile" />
      ),
      dataIndex: "mobile",
      key: "mobile",
    },
    {
      title: <FormattedMessage id="pages.status" defaultMessage="Status" />,
      dataIndex: "status",
      key: "status",
      valueType: "select", // 下拉选择类型
      valueEnum: {
        1: {
          text: (
            <FormattedMessage
              id="pages.status.disabled"
              defaultMessage="Disabled"
            />
          ),
          status: "error",
        },
        0: {
          text: (
            <FormattedMessage
              id="pages.status.enabled"
              defaultMessage="Enabled"
            />
          ),
          status: "success",
        },
      },
      sorter: true,
      search: {
        transform: (value) => value,
      },
    },
    {
      title: (
        <FormattedMessage id="pages.user.loginIp" defaultMessage="Login IP" />
      ),
      dataIndex: "loginIp",
      key: "loginIp",
      search: false,
    },
    {
      title: (
        <FormattedMessage
          id="pages.user.loginDate"
          defaultMessage="Login Date"
        />
      ),
      dataIndex: "loginDate",
      key: "loginDate",
      valueType: "dateTime", // 使用 dateTime 类型显示时间
      sorter: true, // 允许排序
      search: false,
    },
    {
      title: (
        <FormattedMessage id="pages.createTime" defaultMessage="Create Time" />
      ),
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime", // 使用 dateTime 类型显示时间
      sorter: true, // 允许排序
      search: false,
    },
    {
      title: (
        <FormattedMessage id="pages.operating" defaultMessage="Operating" />
      ),
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      // width: 120,
      render: (_, record) => [
        <a
          key="edit"
          onClick={async () => {
            setCurrentRow(record);
            handleUpdateModalOpen(true); // 打开编辑弹窗
          }}
        >
          <FormattedMessage id="pages.edit" defaultMessage="Edit" />
        </a>,
        <a
          key="resetPassword"
          onClick={() => {
            makeResetPwd(record);
            setCurrentRow(record);
          }}
        >
             <FormattedMessage id="password.update.reset" defaultMessage="Reset Password" />
         
        </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={async (key) => {
            if (key === "delete") {
              // 手动触发重置密码逻辑
              await deleteListData(record);
              setCurrentRow(record);
            } else if (key === "activte") {
              await changeUserStatus(record);
              setCurrentRow(record);
            } else if (key === "reload") {
              actionRef.current?.reload();
            }
            // 可以根据需要扩展其他菜单项的逻辑
          }}
          menus={[
            {
              key: "activte",
              name:
                record.status == 1 ? (
                  <FormattedMessage
                    id="pages.status.enabled"
                    defaultMessage="enabled"
                  />
                ) : (
                  <FormattedMessage
                    id="pages.status.disabled"
                    defaultMessage="disabled"
                  />
                ),
            },
            {
              key: "delete",
              name: (
                 <FormattedMessage id="pages.delete" defaultMessage="Delete" />
              ),
              danger: true,
            }, // 新增重置密码菜单项
          ]}
        />,
      ],
    },
  ];

  return (
    <PageContainer title={false}>
      <ProTable<UserVO, API.PageParams>
        headerTitle={intl.formatMessage({
          id: "pages.user.list",
          defaultMessage: "User List",
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined />{" "}
            <FormattedMessage id="pages.user.create" defaultMessage="New" />
          </Button>,
        ]}
        request={pageQueryCustomer}
        columns={columns}
      />

      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => {
          handleModalOpen(false);
        }}
        onSuccess={function (): void {
          handleModalOpen(false);
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      ></AddForm>

      <AddForm
        visible={updateModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      ></AddForm>
    </PageContainer>
  );
};

export default TableList;
